{% load static %}
<form id="asset-form" method="post" action="{% if asset %}{% url 'assets:asset_update' asset.id %}{% else %}{% url 'assets:asset_create' %}{% endif %}" enctype="multipart/form-data" class="card-like">
  {% csrf_token %}
  <div class="row">
    <div class="col-md-6">
      <div class="mb-3">
        <label for="name" class="form-label">资产名称 *</label>
        <input type="text" class="form-control" id="name" name="name" value="{% if asset %}{{ asset.name }}{% else %}{{ name|default:'' }}{% endif %}" required>
      </div>
    </div>
    <div class="col-md-6">
      <div class="mb-3">
        <label for="asset_number" class="form-label">资产编号 *</label>
        <input type="text" class="form-control" id="asset_number" name="asset_number" value="{% if asset %}{{ asset.asset_number }}{% else %}{{ asset_number|default:'' }}{% endif %}" required>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-md-6">
      <div class="mb-3">
        <label for="category" class="form-label">资产类别 *</label>
        <select class="form-select" id="category" name="category" required>
          <option value="">请选择资产类别</option>
          {% for category in categories %}
            <option value="{{ category.id }}" {% if asset and asset.category_id == category.id or category_id|add:"0" == category.id %}selected{% endif %}>{{ category.name }}</option>
          {% endfor %}
        </select>
      </div>
    </div>
    <div class="col-md-6">
      <div class="mb-3">
        <label for="status" class="form-label">资产状态 *</label>
        <select class="form-select" id="status" name="status" required>
          <option value="idle" {% if asset and asset.status == 'idle' or status == 'idle' %}selected{% endif %}>闲置</option>
          <option value="in_use" {% if asset and asset.status == 'in_use' or status == 'in_use' %}selected{% endif %}>在用</option>
          <option value="borrowed" {% if asset and asset.status == 'borrowed' or status == 'borrowed' %}selected{% endif %}>已借出</option>
          <option value="maintenance" {% if asset and asset.status == 'maintenance' or status == 'maintenance' %}selected{% endif %}>维修中</option>
          <option value="faulty" {% if asset and asset.status == 'faulty' or status == 'faulty' %}selected{% endif %}>故障</option>
          <option value="scrapped" {% if asset and asset.status == 'scrapped' or status == 'scrapped' %}selected{% endif %}>已报废</option>
        </select>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-md-6">
      <div class="mb-3">
        <label for="organization" class="form-label">所属组织（账簿归属）</label>
        <select class="form-select" id="organization" name="organization">
          <option value="">请选择组织</option>
          {% if organizations %}
            {% for org in organizations %}
              <option value="{{ org.id }}" {% if asset and asset.ledger and asset.ledger.organization_id == org.id %}selected{% elif organization_id|add:"0" == org.id %}selected{% endif %}>{{ org.name }}</option>
            {% endfor %}
          {% endif %}
        </select>
      </div>
    </div>
    <div class="col-md-6">
      <div class="mb-3" id="ledger-field">
        <label for="ledger" class="form-label">账簿</label>
        <select class="form-select" id="ledger" name="ledger">
          <option value="">请选择账簿</option>
          {% if ledgers %}
            {% for ledger in ledgers %}
              <option value="{{ ledger.id }}" data-org="{{ ledger.organization.id }}" data-org-name="{{ ledger.organization.name }}" data-code="{{ ledger.code }}" {% if asset and asset.ledger_id == ledger.id %}selected{% elif ledger_id|add:"0" == ledger.id %}selected{% endif %}>
                {% if not organization_id %}
                  {% if not asset or not asset.ledger or not asset.ledger.organization_id %}
                    {{ ledger.organization.name }} /
                  {% endif %}
                {% endif %}
                {{ ledger.name }}
              </option>
            {% endfor %}
          {% endif %}
        </select>
        <div class="form-text" id="ledger-help-normal">可先选择“所属组织”以便仅显示该组织下的账簿。</div>
        <div class="form-text text-warning d-none" id="ledger-help-empty">该组织下暂无账簿，将仅使用“所属组织”来标识资产归属，可直接提交。</div>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-md-6">
      <div class="mb-3">
        <label for="department" class="form-label">所属部门</label>
        <select class="form-select" id="department" name="department">
          <option value="">请选择部门</option>
          {% for department in departments %}
            <option value="{{ department.id }}" {% if asset and asset.department_id == department.id or department_id|add:"0" == department.id %}selected{% endif %}>{{ department.name }}</option>
          {% endfor %}
        </select>
      </div>
    </div>
    <div class="col-md-6">
      <div class="mb-3">
        <label for="location" class="form-label">位置</label>
        <select class="form-select" id="location" name="location">
          <option value="">请选择位置</option>
          {% for location in locations %}
            <option value="{{ location.id }}" {% if asset and asset.location_id == location.id or location_id|add:"0" == location.id %}selected{% endif %}>{{ location.name }}</option>
          {% endfor %}
        </select>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-md-6">
      <div class="mb-3">
        <label for="user" class="form-label">使用人</label>
        <select class="form-select" id="user" name="user">
          <option value="">请选择使用人</option>
          {% for user in users %}
            <option value="{{ user.id }}" {% if asset and asset.user_id == user.id or user_id|add:"0" == user.id %}selected{% endif %}>{{ user.username }}</option>
          {% endfor %}
        </select>
      </div>
    </div>
    <div class="col-md-6">
      <div class="mb-3">
        <label for="supplier" class="form-label">供应商</label>
        <select class="form-select" id="supplier" name="supplier">
          <option value="">请选择供应商</option>
          {% for supplier in suppliers %}
            <option value="{{ supplier.id }}" {% if asset and asset.supplier_id == supplier.id or supplier_id|add:"0" == supplier.id %}selected{% endif %}>{{ supplier.name }}</option>
          {% endfor %}
        </select>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-md-6">
      <div class="mb-3">
        <label for="contract" class="form-label">合同</label>
        <select class="form-select" id="contract" name="contract">
          <option value="">请选择合同</option>
          {% for contract in contracts %}
            <option value="{{ contract.id }}" {% if asset and asset.contract_id == contract.id or contract_id|add:"0" == contract.id %}selected{% endif %}>{{ contract.name }}</option>
          {% endfor %}
        </select>
      </div>
    </div>
    <div class="col-md-6">
      <div class="mb-3">
        <label for="purchase_date" class="form-label">启用日期 *</label>
        <input type="date" class="form-control" id="purchase_date" name="purchase_date" value="{% if asset %}{{ asset.purchase_date|date:'Y-m-d' }}{% else %}{{ purchase_date|default:'' }}{% endif %}" required>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-md-6">
      <div class="mb-3">
        <label for="purchase_price" class="form-label">采购价格 *</label>
        <input type="number" class="form-control" id="purchase_price" name="purchase_price" step="0.01" value="{% if asset %}{{ asset.purchase_price }}{% else %}{{ purchase_price|default:'' }}{% endif %}" required>
      </div>
    </div>
    <div class="col-md-6">
      <div class="mb-3">
        <label for="warranty_period" class="form-label">保修期(月)</label>
        <input type="number" class="form-control" id="warranty_period" name="warranty_period" value="{% if asset %}{{ asset.warranty_period }}{% else %}{{ warranty_period|default:'' }}{% endif %}">
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-md-6">
      <div class="mb-3">
        <label for="depreciation_rate" class="form-label">折旧率(%)</label>
        <input type="number" class="form-control" id="depreciation_rate" name="depreciation_rate" step="0.01" value="{% if asset %}{{ asset.depreciation_rate }}{% else %}{{ depreciation_rate|default:'' }}{% endif %}">
      </div>
    </div>
  </div>

  <div class="mb-3">
    <label for="description" class="form-label">描述</label>
    <textarea class="form-control" id="description" name="description" rows="3">{% if asset %}{{ asset.description }}{% else %}{{ description|default:'' }}{% endif %}</textarea>
  </div>

  <div class="mb-3">
    <label for="image" class="form-label">资产图片</label>
    {% if asset and asset.get_primary_image_url %}
      <div class="mb-2">
        <img src="{{ asset.get_primary_image_url }}" alt="{{ asset.name }}" style="max-width: 200px; max-height: 200px; object-fit: cover; border-radius: 8px; border: 1px solid #dee2e6;">
        <div class="mt-1"><small class="text-muted">当前图片</small></div>
      </div>
    {% endif %}
    <input type="file" class="form-control" id="image" name="image" accept="image/*">
    <div class="form-text">支持 JPG、PNG、GIF 格式，建议尺寸不超过 2MB</div>
  </div>

  <div class="mb-3">
    <label class="form-label">额外图片 
      {% if asset %}
        <small class="text-muted">(当前: {{ asset.get_image_count }}/10)</small>
      {% else %}
        <small class="text-muted">(最多10张)</small>
      {% endif %}
    </label>
    <div id="additional-images">
      {% if asset %}
        {% for img in asset.asset_images.all %}
          <div class="d-flex align-items-center mb-2 existing-image" data-image-id="{{ img.id }}">
            <img src="{{ img.get_image_url }}" alt="{{ img.title }}" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px; margin-right: 10px;">
            <div class="flex-grow-1">
              <input type="text" class="form-control form-control-sm mb-1" name="existing_image_title_{{ img.id }}" value="{{ img.title }}" placeholder="图片标题">
              <textarea class="form-control form-control-sm" name="existing_image_description_{{ img.id }}" rows="2" placeholder="图片描述">{{ img.description }}</textarea>
            </div>
            <button type="button" class="btn btn-sm btn-outline-danger ms-2" onclick="removeExistingImage('{{ img.id }}')">
              <i class="fa fa-trash"></i>
            </button>
          </div>
        {% endfor %}
      {% endif %}
    </div>
    {% if not asset or asset.can_add_more_images %}
      <button type="button" class="btn btn-sm btn-outline-primary" onclick="addImageUpload()">
        <i class="fa fa-plus"></i> 添加图片
      </button>
    {% else %}
      <small class="text-muted">已达到图片上限</small>
    {% endif %}
  </div>

  <div class="mb-3 d-flex gap-2">
    <button id="submit-btn" type="submit" class="btn btn-primary">{% if asset %}更新{% else %}创建{% endif %}</button>
    <button id="cancel-btn" type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">关闭</button>
  </div>
</form>

<script>
// The JS below is a subset adapted for inline modal usage (no iframe)
let imageUploadCounter = 0;
const maxImages = 10;
function addImageUpload() {
  const existingImages = document.querySelectorAll('.existing-image').length;
  const newImages = document.querySelectorAll('.new-image-upload').length;
  const mainImage = document.querySelector('input[name="image"]').files.length;
  if (existingImages + newImages + mainImage >= maxImages) { alert(`最多只能上传${maxImages}张图片`); return; }
  imageUploadCounter++;
  const container = document.getElementById('additional-images');
  const imageUploadDiv = document.createElement('div');
  imageUploadDiv.className = 'd-flex align-items-start mb-2 new-image-upload';
  imageUploadDiv.innerHTML = `
    <div class="flex-grow-1">
      <input type="file" class="form-control form-control-sm mb-1" name="additional_images_${imageUploadCounter}" accept="image/*" onchange="validateImageFile(this)">
      <input type="text" class="form-control form-control-sm mb-1" name="additional_image_title_${imageUploadCounter}" placeholder="图片标题">
      <textarea class="form-control form-control-sm" name="additional_image_description_${imageUploadCounter}" rows="2" placeholder="图片描述"></textarea>
    </div>
    <button type="button" class="btn btn-sm btn-outline-danger ms-2" onclick="removeImageUpload(this)"><i class="fa fa-trash"></i></button>`;
  container.appendChild(imageUploadDiv);
}
function validateImageFile(input) {
  const file = input.files[0];
  if (file) {
    if (file.size > 2 * 1024 * 1024) { alert('图片文件大小不能超过2MB'); input.value = ''; return false; }
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
    if (!allowedTypes.includes(file.type)) { alert('只支持 JPG、PNG、GIF 格式的图片'); input.value = ''; return false; }
  }
  return true;
}
function removeImageUpload(button) { button.closest('.new-image-upload').remove(); }
function removeExistingImage(imageId) {
  if (confirm('确定要删除这张图片吗？')) {
    const imageDiv = document.querySelector(`[data-image-id="${imageId}"]`);
    if (imageDiv) imageDiv.style.display = 'none';
    const hiddenInput = document.createElement('input');
    hiddenInput.type = 'hidden';
    hiddenInput.name = 'delete_images';
    hiddenInput.value = imageId;
    document.querySelector('form').appendChild(hiddenInput);
  }
}

(function(){
  const orgSelect = document.getElementById('organization');
  const ledgerSelect = document.getElementById('ledger');
  const ledgerField = document.getElementById('ledger-field');
  const ledgerHelpNormal = document.getElementById('ledger-help-normal');
  const ledgerHelpEmpty = document.getElementById('ledger-help-empty');
  if (!orgSelect || !ledgerSelect) return;
  const allLedgerOptions = Array.from(ledgerSelect.querySelectorAll('option')).filter(opt => opt.value !== '');
  const placeholder = ledgerSelect.querySelector('option[value=""]');
  function getFilteredLedgerOptions(orgId) {
    return !orgId ? allLedgerOptions : allLedgerOptions.filter(opt => String(opt.getAttribute('data-org')) === String(orgId));
  }
  function rebuildLedgerOptions(orgId){
    const prevSelected = ledgerSelect.value;
    ledgerSelect.innerHTML=''; if (placeholder) ledgerSelect.appendChild(placeholder.cloneNode(true));
    const fragment = document.createDocumentFragment();
    const toShow = getFilteredLedgerOptions(orgId);
    toShow.forEach(opt => fragment.appendChild(opt.cloneNode(true)));
    ledgerSelect.appendChild(fragment);
    if (prevSelected && Array.from(ledgerSelect.options).some(o => o.value === prevSelected)) {
      ledgerSelect.value = prevSelected;
    } else {
      ledgerSelect.value = '';
    }
    const availableCount = Array.from(ledgerSelect.options).filter(o => o.value !== '').length;
    if (availableCount === 0){
      ledgerField.classList.add('d-none');
      ledgerHelpNormal?.classList.add('d-none');
      ledgerHelpEmpty?.classList.remove('d-none');
    } else {
      ledgerField.classList.remove('d-none');
      ledgerHelpNormal?.classList.remove('d-none');
      ledgerHelpEmpty?.classList.add('d-none');
    }
  }
  function selectDefaultLedgerForOrg(orgId){
    const options = Array.from(ledgerSelect.options).filter(o => o.value !== '');
    if (options.length === 0) { ledgerSelect.value = ''; return; }
    const current = ledgerSelect.value;
    if (current && options.some(o => o.value === current)) return;
    if (options.length === 1){ ledgerSelect.value = options[0].value; return; }
    ledgerSelect.value = options[0].value;
  }
  rebuildLedgerOptions(orgSelect.value); selectDefaultLedgerForOrg(orgSelect.value);
  orgSelect.addEventListener('change', function(e){ rebuildLedgerOptions(e.target.value); selectDefaultLedgerForOrg(e.target.value); });
})();
</script>
